from alipay import AliPay
from django.shortcuts import render

# Create your views here.
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import OrderingFilter
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework.viewsets import ModelViewSet

from goods.models import Goods, Order, UserGoods
from goods.serializers import GoodsSer
from goods.utils import get_order_id, get_alipay_url, alipay
from syl import settings


class GoodsView(ModelViewSet):
    permission_classes = (IsAuthenticated,)
    #登录才能查看商品价格等信息
    queryset = Goods.objects.all()
    serializer_class = GoodsSer
    #指定过滤方法类, 排序方法类, 一个或多个
    filter_backends = (DjangoFilterBackend, OrderingFilter)  # 同时支持过滤和排序

    # 指定排序字段, 不设置, 排序功能不起效
    # ordering_fields = ('date_joined', 'id')

    # 指定过滤字段, 不设置, 过滤功能不起效
    filter_fields = ('course', 'pay_type', 'is_launched')

    # 自定义分页器 覆盖全局配置
    # pagination_class = PageNum

class PayUrlView(APIView):
    permission_classes = (IsAuthenticated,)
    def post(self,request):
        # 1. 获取课程id,获取购买途径(普通购买, 促销购买) 获取用户
        goods_id = request.data.get("goods_id")
        print(goods_id,"goods_id")
        goods= Goods.objects.get(id=goods_id)
        user = request.user
        print('user',user)
        # 2. 下定单
        order_id = get_order_id()
        print(order_id)
        order = Order(user=user,goods=goods,orderid=order_id,pay_method=1,status=1,sum_price=goods.price)
        order.save()
        # 3. 根据订单 生成支付链接

        subject = "实验楼订单:%s, 价格:%s" % (order.orderid, order.sum_price)
        pay_url = get_alipay_url(order.orderid, order.sum_price, subject)
        # 4. 返回链接
        return Response({"code": 0, "msg": "下单成功", "data": {"pay_url": pay_url}})


class PayMentView(APIView):
    permission_classes = (AllowAny,)
    def post(self, request):
        # 1. 获取了支付宝返回的数据

        query = request.data.get("query")
        # 2.
        # query.pop('sign_type')
        sign = query.pop('sign')
        print("query2",query)
        success = alipay.verify(query, sign)
        print('success',success)
        if not success:
            return Response({"code": 999, "msg": "非法请求"})
        # 跟新订单状态
        order = Order.objects.get(order_id=query['out_trade_no'])
        order.trade_no = query['trade_no']
        order.pay_time = query['timestamp']
        order.status = 2
        order.save()
        # 3. 处理用户购买课程流程
        # 3.1 给 UserCourse 表增加 购买记录
        goods = order.goods
        UserGoods(user=order.user, goods_course=goods).save()

        return Response({"code":200,"msg":"购买成功"})